﻿using UnityEngine;
using UnityEngine.Playables;

namespace GameToolkit
{
    public class PlaybackMark : PlayableAsset
    {
        public enum EPauseTrigger
        {
            None,
            PauseOnStart,
            PauseOnEnd,
        }

        [SerializeField]
        EPauseTrigger m_PauseTrigger;

        public override Playable CreatePlayable(PlayableGraph graph, GameObject owner)
        {
            var playable = ScriptPlayable<MarkBehaviour>.Create(graph);
            var mark = playable.GetBehaviour();
            mark.Mark = this;
            return playable;
        }

        internal class MarkBehaviour : PlayableBehaviour
        {
            bool mPlayed;
            internal PlaybackMark Mark { get; set; }

            internal PlaybackAction mAction;

            public override void OnBehaviourPlay(Playable playable, FrameData info)
            {
                mPlayed = true;
                if (Mark != null && Mark.m_PauseTrigger == EPauseTrigger.PauseOnStart && mAction != null)
                {
                    mAction.PauseTimeline();
                }
            }

            public override void OnBehaviourPause(Playable playable, FrameData info)
            {
                if (mPlayed && Mark != null && Mark.m_PauseTrigger == EPauseTrigger.PauseOnEnd && mAction != null)
                {
                    mAction.PauseTimeline();
                }
                mPlayed = false;
            }
        }
    }
}
